package com.learn.gateway.filter;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.google.common.util.concurrent.RateLimiter;
import com.learn.gateway.exception.RateLimiterExeception;
import com.netflix.zuul.ZuulFilter;

/** Google令牌限流 */
@Component
public class RateLimitFilter extends ZuulFilter {

	/** 每秒生成99个令牌 */
	private static final RateLimiter rateLimiter = RateLimiter.create(99);

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return FilterConstants.SERVLET_DETECTION_FILTER_ORDER - 1;
	}

	@Override
	public Object run() {
		if(!rateLimiter.tryAcquire()) throw new RateLimiterExeception();
		return null;
	}

}
